
import React, {useState,useEffect} from "react";
import {trim} from "lodash";
import {Modal, Form, Input,DatePicker} from "antd/lib";
import { wrap as wrapDialog, DialogPropType } from "@/components/DialogWrapper";
import DynamicComponent from "@/components/DynamicComponent";
import {policy} from "@/services/policy";
import {UserProfile} from "@/components/proptypes";
import notification from "@/services/notification";
import TimeSerial from "@/services/timeSerial";
import moment from "moment";

  function TimeSerialDialog({ timeserial_item, dialog }) {
    const [dataLoaded, setDataLoaded] = useState(timeserial_item.id ===0 ? true : false);
    const [num, setnum] = useState("");
    const [name, sename] = useState("");
    const [begin_date, setbegin_date] = useState("");
    const [close_date, setclose_date] = useState("");
    const [isValid, setIsValid] = useState(false);
    const [saveInProgress, setSaveInProgress] = useState(false);
    const isCreateTimeSerialEnabled =useState(true);// policy.isAdmin() || policy.isDefault();
  
    useEffect(() => {
      let cancelLoading = false;
        if (!cancelLoading) {
          setnum(timeserial_item.num);
          sename(timeserial_item.name);
          setbegin_date(timeserial_item.begin_date);
          setclose_date(timeserial_item.close_date);
          setDataLoaded(true);
      }
  
      return () => {
        cancelLoading = true;
      };
    }, [timeserial_item]);
  
    function handlenumChange(event) {
      const value = trim(event.target.value);
      setnum(value);
      setIsValid(value !== "" && name !== "" && begin_date !== "" && close_date !== "");
    }
  
    function handleNameChange(event) {
      const value = trim(event.target.value);
      sename(value);
      setIsValid(value !== "" && num !== "" && begin_date !== "" && close_date !== "");
    }
    function handlebegin_dateChange(event) {
      const value = trim(event.target.value);
      setbegin_date(value);
      setIsValid(value !== "" && num !== "" && name !== "" && close_date !== "");
    }
    function handleclose_dateChange(event) {
      const value = trim(event.target.value);
      setclose_date(value);
      setIsValid(value !== "" && num !== "" && name !== "" && begin_date !== "");
    }
  
    function handleSubmit() {
      setSaveInProgress(true);
  
      if (timeserial_item.id === 0) {
        let timevalue =  {
          num: num,
          name: name,
          calendar_enum: timeserial_item.calendar_enum,
          timestruct_id: timeserial_item.timestruct_id,
          parent_id: timeserial_item.parent_id,
          begin_date:  begin_date,
          close_date: close_date
        };
        TimeSerial.create(timevalue)
          .then(() => {
            dialog.close({ success: true});
          })
          .catch(error => {
            notification.error(error.message, error.detailedMessage);
            setSaveInProgress(false);
          });
      } else {
        let timevalue =  {
          id: timeserial_item.id,
          num: num,
          name: name,
          calendar_enum: timeserial_item.calendar_enum,
          timestruct_id: timeserial_item.timestruct_id,
          parent_id: timeserial_item.parent_id,
          begin_date:  begin_date,
          close_date: close_date
        };
        TimeSerial.save(timevalue)
          .then(() => {
            dialog.close({ success: true});
          })
          .catch(error => {
            notification.error(error.message, error.detailedMessage);
            setSaveInProgress(false);
          });
      }
    }
  
    return (
      <Modal
        {...dialog.props}
        {...(isCreateTimeSerialEnabled ? {} : { footer: null })}
        title={ timeserial_item.id ===0 ? "新建时间序列节点" : "修改时间序列节点"}
        okText={ timeserial_item.id ===0 ? "新建" : "保存"}
        cancelText="取消"
        okButtonProps={{
          disabled: !isValid || saveInProgress,
          loading: saveInProgress,
          "data-test": "DashboardSaveButton",
        }}
        cancelButtonProps={{
          disabled: saveInProgress,
        }}
        onOk={handleSubmit}
        closable={!saveInProgress}
        maskClosable={!saveInProgress}
        wrapProps={{
          "data-test": "CreateDashboardDialog",
        }}>
        {dataLoaded && (
        <DynamicComponent name="CreateTimeSerialDialogExtra" disabled={!isCreateTimeSerialEnabled}>
        <Form>
          <Form.Item style={{ marginBottom: 5 }} label="代号">
          <Input
            defaultValue={num}
            onChange={handlenumChange}
            placeholder="代号"
            disabled={saveInProgress}
            autoFocus
          />
          </Form.Item>
          <Form.Item style={{ marginBottom: 5 }} label="名称">
          <Input
            defaultValue={name}
            onChange={handleNameChange}
            placeholder="名称"
            disabled={saveInProgress}
          />
          </Form.Item>
          <Form.Item style={{ marginBottom: 5 }} label="开始日期">
          <DatePicker
            defaultValue={moment(begin_date)}
            format='YYYY-MM-DD'
            onChange={handlebegin_dateChange}
            placeholder="开始日期"
            disabled={saveInProgress}
          />
          </Form.Item>
          <Form.Item style={{ marginBottom: 5 }} label="结束日期">
          <DatePicker
            defaultValue={moment(close_date)}
            onChange={handleclose_dateChange}
            placeholder="结束日期"
            disabled={saveInProgress}
          />
          </Form.Item>
        </Form>
        </DynamicComponent>
        )}
      </Modal>
    );
  }
  
  TimeSerialDialog.propTypes = {
    timeserial_item: UserProfile.isRequired,
    dialog: DialogPropType.isRequired,
  };
  
  export default wrapDialog(TimeSerialDialog);
